package cn.clq.system.controller;

import cn.clq.basic.annotation.PreAuthorize;
import cn.clq.system.service.IMenuService;
import cn.clq.system.domain.Menu;
import cn.clq.system.query.MenuQuery;
import cn.clq.basic.util.AjaxResult;
import cn.clq.basic.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/menu")
public class MenuController {
    @Autowired
    private IMenuService menuService;


    /**
     * 保存和修改公用的
     * @param menu  传递的实体
     * @return Ajaxresult转换结果
     */
    @PreAuthorize(name = "新增修改菜单",value = "menu:addOrUpdate")
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Menu menu){
        try {
            if( menu.getId()!=null)
                menuService.update(menu);
            else
                menuService.save(menu);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("保存菜单失败！"+e.getMessage());
        }
    }
    /**
    * 删除菜单信息
    * @param id
    * @return
    */
    @PreAuthorize(name = "删除菜单",value = "menu:delete")
    @DeleteMapping(value="/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            menuService.removeById(id);
            return AjaxResult.me();
        } catch (Exception e) {
        e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除菜单失败！"+e.getMessage());
        }
    }
	
    //获取菜单
    @GetMapping("/{id}")
    public Menu get(@PathVariable("id")Long id)
    {
        return menuService.queryById(id);
    }


    /**
    * 查看所有的菜单信息
    * @return
    */
    @GetMapping()
    public List<Menu> list(){

        return menuService.queryAll();
    }


    /**
    * 分页查询数据
    *
    * @param query 查询菜单
    * @return PageList 分页菜单
    */
    @PreAuthorize(name = "菜单高级分页查询",value = "menu:list")
    @PostMapping("/list")
    public PageList<Menu> json(@RequestBody MenuQuery query)
    {
        return menuService.queryPage(query);
    }

    @PreAuthorize(name = "查询菜单无限级树",value = "menu:tree")
    @GetMapping("/tree")
    public List<Menu> getMenuTree(){
        return menuService.getMenuTree();
    }
}
